<template>
  <el-scrollbar height="500px">
    <el-tree :data="libTree" :props="defaultProps" :indent="10" @node-click="handleNodeClick" :default-expand-all="true">
      <template #default="{ data }">
        <span class="custom-tree-node">
          <i class="iconfont custom-tree-icon" :style="{ color: getFileTypeInfo(data).color }">
            {{ getFileTypeInfo(data).icon }}
          </i>
          <span>{{ getName(data) }}</span>
        </span>
      </template>
    </el-tree>
  </el-scrollbar>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import { getLibTree } from '@/api/file'

const defaultProps = {
  children: 'children',
  label: 'name'
}

// 文件类型配置对象
const FILE_TYPES = {
  folder: {
    icon: '\ue80c',
    color: '#dcb67a'
  },
  js: {
    icon: '\ue639',
    color: '#f1e05a'
  },
  css: {
    icon: '\ue63d',
    color: '#563d7c'
  },
  image: {
    icon: '\ue85b',
    color: '#2dcc9f'
  },
  default: {
    icon: '\ue70d',
    color: '#6e7681'
  }
}

// 图片文件扩展名列表
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif']

const getFileTypeInfo = data => {
  if (data.isFolder) {
    return FILE_TYPES.folder
  }

  const ext = data.name.split('.').pop().toLowerCase()

  if (FILE_TYPES[ext]) {
    return FILE_TYPES[ext]
  }

  if (IMAGE_EXTENSIONS.includes(ext)) {
    return FILE_TYPES.image
  }

  return FILE_TYPES.default
}

const libTree = ref([])

const _getLibTree = async () => {
  const res = await getLibTree()
  if (res.code === 20000) {
    libTree.value = res.data
  }
}
_getLibTree()

const getName = (data) => {
    // 如果是文件夹，按/分割，取倒数第二个，否则分割后取倒数第一个
    const arr = data.name.split('/')
    return data.isFolder ? arr[arr.length - 2] : arr[arr.length - 1]
}

const handleNodeClick = data => {
  if (!data.isFolder) {
    const { copy } = useClipboard()
    const extension = data.name.split('.').pop()
    let text = ''
    if (extension === 'js') {
      text = '<script src="${libPath}' + `${data.url}"><\/script>`
    } else if (extension === 'css') {
      text = '<link rel="stylesheet" type="text/css" href="${libPath}' + `${data.url}" />`
    } else if (extension === 'ftl') {
      text = '<#include "${libPath}' + `${data.url}">`
    } else {
      text = '${libPath}' + `${data.url}`
    }
    
    copy(text).then(() => {
      ElMessage.success('复制路径成功')
    }).catch(() => {
      ElMessage.error('复制路径失败')
    })
  }
}
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.custom-tree-icon {
  margin-right: 8px;
  font-size: 16px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #f5f5f5;
}
</style>
